import store from '@/store'
import config from '@/config'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { toast, showConfirm, tansParams } from '@/utils/common'

const appidMap = {
  'work-safety': '1760901010825080833'
}
export let isRelogin = { show: false }
class RequestBase {
  constructor(domain, header = {}) {
    this._domain = domain
    this._header = {
      'content-type': 'application/json',
      ...header
    }
  }
  /**
   * 配置其他头部
   */
  generateHeader(options = {}) {
    let header = {}
    const isToken = (options || {}).isToken === false
    if (getToken() && !isToken) {
      header.Authorization = getToken()
    } else {
      header.Authorization = ''
    }
    // #ifdef APP-PLUS
    header.version = store.state.deviceInfo.version
    header.systemInfo = store.state.deviceInfo.systemInfo
    // #endif
    // 判断当前appid
    const current = this._domain.split('/api/')[1]
    if (appidMap[current]) {
      header['X-Aggregation-App-Id'] = config.aggregationAppid
      header['X-App-Id'] = appidMap[current]
    } else {
      header['X-App-Id'] = config.aggregationAppid
    }
    return {
      ...header,
      ...options
    }
  }

  /**
   * GET类型的网络请求
   */
  get(url, data, header) {
    return this.request(url, data, header, 'GET')
  }

  /**
   * DELETE类型的网络请求
   */
  delete(url, data, header) {
    return this.request(url, data, header, 'DELETE')
  }

  /**
   * PUT类型的网络请求
   */
  put(url, data, header) {
    return this.request(url, data, header, 'PUT')
  }

  /**
   * POST类型的网络请求
   */
  post(url, data, header) {
    return this.request(url, data, header, 'POST')
  }

  /**
   * 网络请求
   */
  request(url, data, header, method) {
    return new Promise((resolve, reject) => {
      uni
        .request({
          method: method,
          url: `${this._domain}${url}`,
          data: data,
          header: this.generateHeader(header),
          dataType: 'json',
          sslVerify: false
        })
        .then((response) => {
          let [error, res] = response
          if (error) {
            let errMsg = '网络连接异常'
            toast(errMsg)
            reject(errMsg)
            return
          }
          const code = res.data.status || res.data.code || 200
          const msg = errorCode[code] || res.data.msg || errorCode['default']
          if (code === 401 && !store.state.system.expired) {
            const pages = getCurrentPages()
            let isUpgradePage = false
            if (pages.length > 0) {
              const page = pages[pages.length - 1]
              isUpgradePage = page.route && page.route.includes('pages/upgrade/upgrade')
            }
            console.log('isUpgradePage', isUpgradePage)
            if (!isUpgradePage) {
              store.dispatch('SET_EXPIRED', true)
              if (!isRelogin.show) {
                isRelogin.show = true
                showConfirm('登录状态已过期，您可以继续留在该页面，或者重新登录?').then((res) => {
                  if (res.confirm) {
                    const pages = getCurrentPages()
                    let isUpgradePage = false
                    if (pages.length > 0) {
                      const page = pages[pages.length - 1]
                      isUpgradePage = page.route && page.route.includes('pages/upgrade/upgrade')
                    }
                    if (!isUpgradePage) {
                      store.dispatch('LogOut').then((res) => {
                        uni.reLaunch({ url: '/pages/login' })
                      })
                    }
                  }
                  if (res.cancel) {
                    isRelogin.show = false
                    store.dispatch('SET_EXPIRED', false)
                  }
                })
              }
            }
            reject(msg)
          } else if (res.statusCode === 404) {
            reject('404')
          } else if (code === 500) {
            if (msg) {
              toast(msg)
            }
            reject('500')
          } else if (code !== 200) {
            reject({
              code,
              msg
            })
          } else {
            resolve(res.data)
          }
        })
        .catch((error) => {
          let { message } = error
          if (message === 'Network Error') {
            message = '后端接口连接异常'
          } else if (message.includes('timeout')) {
            message = '系统接口请求超时'
          } else if (message.includes('Request failed with status code')) {
            message = '系统接口' + message.substr(message.length - 3) + '异常'
          }
          toast(message)
          reject(error)
        })
    })
  }
}
// 请求拦截
uni.addInterceptor('request', {
  invoke(args) {
    const token = getToken()
    const whiteList = ['login', 'apk/newest', 'smsLogin', 'sendSmsCode', 'modify-password']
    if (!whiteList.some((url) => args.url.includes(url)) && !token) {
      uni.reLaunch({
        url: '/pages/login/login'
      })
      return false
    }
    if (args.data?.showLoading || args.header?.showLoading) {
      // 显示请求loading
      uni.showLoading({
        title: '请求中，请稍候...',
        mask: true
      })
    }
    return true
  },
  success(args) {
    // 成功回调拦截
  },
  fail(err) {
    // 失败回调拦截
    console.log(err)
    toast('网络异常！', 'error')
  },
  complete(res) {
    // 完成回调拦截
    uni.hideLoading()
  }
})

export const request = new RequestBase(config.baseUrl)
export default RequestBase
